import { MathUtil } from './utils/MathUtil';
import Game from './Game';
import { ColliderGroups } from './constants/Enums';
import Bullet from './Bullet';
import Player from './Player';
// import { ColliderGroups } from "./constants/Enums";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Enemy1 extends cc.Component {
	/**
     * 子弹垂直方向速度.
     */
	@property({ type: cc.Integer })
    ySpeed = 0;
    
    @property(cc.SpriteFrame)
    enemy1:cc.SpriteFrame = null;

	/**
     * 移动方向
     */
	down = true;
	/**
     * 游戏主对象.
     */
	game: Game;

	/**
     * 节点中的动画组件
     */
	anim: cc.Animation;

	// LIFE-CYCLE CALLBACKS:

	onLoad() {
		this.init();
	}

	onDestroy(){
		this.anim.off(cc.Animation.EventType.FINISHED,this.recycle,this);
	}

	start() {
		this.anim = this.node.getComponent(cc.Animation);
		//动画播放完成时,回收对象.
		this.anim.on(
			cc.Animation.EventType.FINISHED,
			this.recycle,
			this
		);
	}

	update(dt) {
		//根据当前移动方向每帧更新敌机位置.
		if (this.down) {
			this.node.y -= this.ySpeed * dt;
		}

		//如果敌机一直存活到超出屏幕,则回收.
		// if(this.node.x > this.node.parent.width/2 + this.node.width/2){
		// }else if(this.node.x < - this.node.parent.width/2 - this.node.width/2){
		// }
		// if(this.node.y > this.node.parent.height/2 + this.node.height/2){
		//     this.destroy();
		// }else
		if (this.node.y < -this.node.parent.height / 2 - this.node.height / 2) {
			this.recycle();
		}
	}

	// LIFE-CYCLE CALLBACKS END

	init() {
		let randX = 0;
		let randY = 0;
		randX = MathUtil.getRandomNumber(-0.9, 0.9) * this.node.parent.width / 2;
		randY = this.node.parent.height / 2 + this.node.height / 2 + MathUtil.getRandomNumber(0, 100);
		this.node.x = randX;
		this.node.y = randY;

		//恢复因播放动画取消的移动速度.
        this.ySpeed = this.ySpeed;
        
        //解决重用敌机对象后,依然显示爆炸效果的问题.
        this.node.getComponent(cc.Sprite).spriteFrame = this.enemy1;
	}

	/**
     * 当碰撞产生的时候调用
     * @param  {cc.Collider} other 产生碰撞的另一个碰撞组件
     * @param  {cc.Collider} self  产生碰撞的自身的碰撞组件
     */
	onCollisionEnter(other: cc.Collider, self: cc.Collider) {
		// if(other.node.group === ColliderGroups.Player){
		// }
		if (other.node.group === ColliderGroups.PlayerBullet) {
            this.game.gainScore();
        }
        //取消撞击检测.防止被第一发子弹撞到后,后面的子弹继续触发撞击检测.
		this.node.group = ColliderGroups.Default;
		this.playAnimationAndRecycle();
	}

	/**
     * 播放爆炸动画,并回收对象.
     */
	playAnimationAndRecycle() {
		// 播放爆炸动画
		this.anim.play('enemy1_explode');
	}
	/**
     * 回收到对象池.
     */
	recycle() {
		this.game.enemy1Count--;

		//退回资源池.
		this.game.pool.putEnemy1(this.node);
		// this.game = null;
	}
}
